import JSEncrypt from 'jsencrypt'

interface JSEncryptSingleton {
  getEncryptInstance: (publicKey: string) => JSEncrypt
}

class JSEncryptSingletonFactory implements JSEncryptSingleton {
  private static instanceMap: Map<string, JSEncrypt> = new Map()

  getEncryptInstance(publicKey: string): JSEncrypt {
    if (!JSEncryptSingletonFactory.instanceMap.has(publicKey)) {
      const encrypt = new JSEncrypt()
      encrypt.setPublicKey(publicKey)
      JSEncryptSingletonFactory.instanceMap.set(publicKey, encrypt)
    }
    return JSEncryptSingletonFactory.instanceMap.get(publicKey) as JSEncrypt
  }
}

export const JsEncryptSingleton: JSEncryptSingleton = new JSEncryptSingletonFactory()
